<template>
  <!-- 登录模态框 -->
  <div class="modal">
    <!-- 遮罩层 -->
    <div class="mask" @click="changeIsShowLoginModal(false)"></div>
    <!-- 登录框 -->
    <div class="loginbox">
      <!-- 关闭按钮 -->
      <div class="close" @click="changeIsShowLoginModal(false)"></div>
      <!-- 切换导航 -->
      <section class="nav">
        <a
          href=""
          @click.prevent="isContentShow = true"
          :class="{ active: isContentShow }"
          >手机登录</a
        >|
        <a
          href=""
          :class="{ active: !isContentShow }"
          @click.prevent="showQrCode"
          >微信登录</a
        >
      </section>
      <div class="content">
        <!-- 手机登录 -->
        <div class="phonelogin" v-show="isContentShow">
          <div class="row">
            <input
              class="ipt"
              v-model="phoneNumber"
              placeholder="请输入手机号"
              type="text"
            />
          </div>
          <!-- <div class="row">
            <input class="ipt" placeholder="请输入密码" type="password" />
          </div> -->
          <!-- 滑动验证码 -->
          <slide-verify
            :l="42"
            :r="20"
            :w="362"
            :h="140"
            @success="onSuccess"
            @fail="onFail"
            @refresh="onRefresh"
            :style="{ width: '100%' }"
            class="slide-box"
            ref="slideBlock"
            :slider-text="msg"
          ></slide-verify>
          <div class="row">
            <input v-model="code" class="ipt" type="text" />
            <!-- <button class="btncode" @click="getCode">
              {{ isShowCount ? count + "s后获取" : "获取验证码" }}
            </button> -->
            <!-- 防止多次开启定时器，受用两个按钮避免 -->
            <button v-show="!isShowCount" class="btncode" @click="getCode">
              获取验证码
            </button>
            <button v-show="isShowCount" class="btncode">
              {{ count + "s后获取" }}
            </button>
          </div>

          <div class="row">
            <button class="btnlogin" @click="submitFn">登录</button>
          </div>
        </div>

        <!-- 微信登陆 -->
        <!-- 二 给展示二维码的容器加id -->
        <div id="weixin" class="qrlogin" v-show="!isContentShow">微信登陆</div>
      </div>
      <!-- 导航对应的内容 -->
    </div>
  </div>
</template>

<script>
import { mapActions, mapMutations } from "vuex";
import { validatePhoneNumber } from "@/utils";
import {
  GetVerificationCodeAPI,
  PhoneLoginAPI,
  WeChatBindingAPI,
  UserProfilesAPI,
} from "@/request/api";
export default {
  data() {
    return {
      phoneNumber: "",
      //模态框
      isContentShow: true,
      msg: "向右滑动",
      //倒计时
      count: 3,
      //是否显示倒计时文字
      isShowCount: false,
      //验证码
      code: "",
    };
  },
  methods: {
    ...mapMutations({
      changeIsShowLoginModal: "showModal/changeIsShowLoginModal",
      changeIsLogined: "loginStatus/changeIsLogined",
      changeIsShowToast: "toastShow/changeIsShowToast",
      updateUserInfo: "userInfo/updateUserInfo",
    }),
    ...mapActions({
      asyncChangeIsShowToast: "toastShow/asyncChangeIsShowToast",
      asyncChangeUserInfo: "userInfo/asyncChangeUserInfo",
    }),
    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
      // console.log(this.msg);
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },
    //显示倒计时
    countDown() {
      this.isShowCount = true;
      let timer = setInterval(() => {
        this.count--;

        if (this.count == 0) {
          //停止定时器
          clearInterval(timer);
          // 显示回获取验证码
          this.isShowCount = false;
          //初始化count
          this.count = 3;
        }
      }, 1000);
    },
    //滑块验证码，手机号输入验证函数
    toVerity() {
      //判断输入的手机号格式，不对的话弹出提示
      if (!validatePhoneNumber(this.phoneNumber)) {
        this.asyncChangeIsShowToast({
          toastMsg: "手机号格式不对",
          toastType: "danger",
        });
        return false;
      }
      //滑动验证码，不正确return
      //如果向右滑动 或 再试一次表示不成功
      if (this.msg == "向右滑动" || this.msg == "再试一次") {
        //弹自定义窗
        this.asyncChangeIsShowToast({
          toastMsg: "请滑动验证码",
          toastType: "danger",
        });
        return false;
      }
      return true;
    },
    //获取验证码
    async getCode() {
      //获取验证码功能（给后台发起请求，）发送成功后会有一个倒计时功能 59s
      //验证手机号格式是否正确
      //验证滑块验证码有没有验证
      if (!this.toVerity()) return;

      //发起请求
      let res = await GetVerificationCodeAPI({
        phone: this.phoneNumber.trim(),
      });
      if (!res) return;
      if (res.code == 0) {
        this.asyncChangeIsShowToast({
          toastMsg: "短信发送成功",
          toastType: "success",
        });
        this.countDown();
      }
    },
    //登录
    async submitFn() {
      //1 验证手机号格式是否正确
      //2 验证滑块验证码有没有验证
      if (!this.toVerity()) return;
      //3 输入短信验证码 验证
      if (!this.code.trim()) {
        //调用自定义弹窗
        this.asyncChangeIsShowToast({
          toastMsg: "请输入短信验证码",
          toastType: "danger",
        });
        return;
      }
      /*  4.发送登录请求 
           分场景
              如果有uuid则表示微信绑定手机号
              否则就是普通的手机验证码登录
     
     */
      let uuid = localStorage.getItem("uuid");
      let res = null;
      if (uuid) {
        res = await WeChatBindingAPI({
          phone: this.phoneNumber.trim(),
          verifyCode: this.code.trim(),
          uuid,
        });
          // 5.删除uuid
      localStorage.removeItem("uuid");
      // 6.清除地址栏中的code
      this.$router.push(this.$route.path);
      } else {
        res = await PhoneLoginAPI({
          verifyCode: this.code.trim(),
          phone: this.phoneNumber.trim(),
        });
      }

      if (!res) return;

      //保存token值 【x-auth-token】
      localStorage.setItem("x-auth-token", res["x-auth-token"]);

      //隐藏登录模态框
      this.changeIsShowLoginModal(false);
      //登陆状态切换
      this.changeIsLogined(true);
    
      //7.登录成功后获取用户信息
      this.asyncChangeUserInfo();
      //调用自定义弹窗
      this.asyncChangeIsShowToast({
        toastMsg: "登录成功",
        toastType: "success",
      });
    },
    //微信扫码登录
    showQrCode() {
      //切换登录窗口
      this.isContentShow = false;
      //获取二维码 并展示
      // 申请微信登录二维码
      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8080" + _this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLC5pbXBvd2VyQm94IC5pbmZvew0KICAgIGRpc3BsYXk6IG5vbmU7DQp9ICAgIA0KLmltcG93ZXJCb3ggcXJjb2Rlew0KICAgIG1hcmdpbi10b3A6IDIwcHg7DQp9",
      });
    },
  },
};
</script>

<style lang="less" scoped>
.modal {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  .mask {
    width: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    height: 100%;
  }
  .close {
    cursor: pointer;
    position: absolute;
    right: 50px;
    top: 10px;
    width: 22px;
    height: 22px;
    background: url("../assets/img/close.png");
  }

  .loginbox {
    width: 555px;
    height: 423px;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    background-color: #fff;
    background: url("../assets/img/login-box-bg.png");
    .nav {
      display: flex;
      justify-content: center;
      padding-top: 20px;
      font-size: 20px;
      a {
        text-decoration: none;
        color: #9a9bb3;
        padding: 0 10px;
        &.active {
          color: #030303;
        }
      }
    }
    .content {
      width: 355px;
      margin: 20px auto 0;
      height: 200px;
      .phonelogin {
        padding-top: 40px;
        .row {
          display: flex;
          margin-bottom: 10px;
        }
        .ipt {
          outline: none;
          flex: 1;
          height: 48px;
          padding-left: 10px;
        }
        button {
          border: none;
          cursor: pointer;
          line-height: 48px;
        }
        .btncode {
          margin-left: 10px;
          width: 100px;
        }
        .btnlogin {
          color: #fff;
          width: 100%;
          background-color: #0a3281;
        }
      }
      .qrlogin {
        display: flex;
        justify-content: center;
      }
    }
  }
}
//滑动验证码样式
/deep/.slide-box {
  width: 100%;
  position: relative;
  margin-bottom: 20px;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>
